<!-- 房屋管理 -->
<template>
  <div>
    <div class="header" style="background: #fff;">
      <div class="title">
        <div style="padding-top: 15px; margin-bottom: 15px">
          <a-space style="margin-left: 13px">
            <span>行政区划：</span>
            <a-input-group compact>
              <a-cascader
                v-model:value="strXzqm"
                style="width: 100%"
                :options="regionList"
                expand-trigger="hover"
                placeholder="行政区"
                changeOnSelect
                @change="onChange"
              />
            </a-input-group>
          </a-space>
          <a-space style="margin-left: 10px">
            <span>开始时间：</span>
            <a-date-picker v-model:value="startDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
          </a-space>
          <a-space style="margin-left: 10px">
            <span>结束时间：</span>
            <a-date-picker v-model:value="endDate" :format="dateFormat"  :disabledDate="disabledFutureDate"  />
          </a-space>
          <a-space style="margin-top: 15px; margin-left: 25px">
            <span>预警类型：</span>
            <a-select
              ref="select"
              v-model:value="remark"
              style="width: 180px"
              placeholder="预警类型"
            >
             <a-select-option value="">预警类型</a-select-option>
              <a-select-option value="区级房屋基本信息与核验不一致"
                >区级房屋基本信息与核验不一致</a-select-option
              >
              <a-select-option value="市级房屋基本信息与核验不一致"
                >市级房屋基本信息与核验不一致</a-select-option
              >
              <a-select-option value="市级和区级核验结果不一致"
                >市级和区级核验结果不一致</a-select-option
              >
              <a-select-option value="区级和市级核验结果不一致"
                >区级和市级核验结果不一致</a-select-option
              >
            </a-select>
          </a-space>
          <a-space style="margin-top: 5px; margin-left: 10px">
            <a-select
              ref="select"
              v-model:value="cs"
              style="width: 350px"
              mode="multiple"
              placeholder="层数"
              @change="handleChange"
            >
              <a-select-option value="1">一层</a-select-option>
              <a-select-option value="2">二层</a-select-option>
              <a-select-option value="3">三层及以上</a-select-option>
            </a-select>
          </a-space>
          <a-space style="margin-top: 5px; margin-left: 10px">
            <a-button
              type="primary"
              @click="searchBtn"
              style="margin-right: 10px; margin-top: 0px; position: relative"
              >查询</a-button
            >
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
           <!-- <space style="float: right; margin-right: 10px; margin-top: 15px">
            <a-button type="primary" @click="handleExport"> 导出统计表</a-button>
          </space> -->
        </div>
      </div>
      <a-table
        :columns="columns"
        :data-source="computedTableData"
        :page-size-options="pageSizeOptions"
        :loading="loading"
        bordered
        :pagination="false"
        size="middle"
        :scroll="{ x: 'calc(700px + 50%)', y: 850 }"
      >
        <!-- <template #action>
            <a>action</a>
          </template> -->
      </a-table>
      <div class="pagination">
        <a-pagination
          show-size-changer
          :show-total="(total) => `共有 ${total} 条记录`"
          v-model:current="pageIndex"
          v-model:pageSize="pageSize"
          :total="total"
          style="float: right"
          @show-size-change="onShowSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import { HomeOutlined, ArrowLeftOutlined } from '@ant-design/icons-vue';
  import { ref, onMounted, onBeforeMount, computed, watch } from 'vue';
  import { gethousingearlyList } from '/@/api/demo/api';
  import { getRegion } from '/@/api/demo/system'; //统计工作进展
  import { useGlobSetting } from '/@/hooks/setting';
  import moment from 'moment';
  import dayjs from 'dayjs';
  import { useUserStore } from '/@/store/modules/user';
  import { downloadByUrl } from '/@/utils/file/download';
  const userStore = useUserStore();
  const router = useRouter();
  const globSetting = useGlobSetting();
  const loading = ref<any>(true);
  // 表格的 ref Dom名称
  const remark = ref<string>('');
  const role_type = ref<string>('');
  const txtKeyWord = ref<string>(''); //核验人员姓名
  const cs = ref<string[]>([]); //层数
  const jsrysstd = ref<string>(''); //是否满足双通道
  const dateFormat = 'YYYY-MM-DD';
  const startDate = ref<any>(null); // 开始时间
  const endDate = ref<any>(null); // 结束时间
  const strXzqm = ref<string[]>([]);
  let regionList = ref<any[]>([]);
  let pageIndex = ref(1);
  let pageSize = ref(20);
  let total = ref(0);

  const disabledFutureDate = (current) => {
  return current && current > moment().endOf('day');
};
  let detailTableHeight = ref<number>(600); // 表格高度
  const pageSizeOptions = ref<string[]>(['100', '200', '300']);
  let tableSource = ref<any>([]);
  // 目标页面读取
  const baseColumns = [
    { title: '序号', width: 50, dataIndex: 'index', key: 'index', align: 'center', fixed: 'left' },
    {
      title: '行政区',
      dataIndex: 'xzq',
      key: 'xzq',
      align: 'center',
      width: 170,
    },
    {
      title: '乡镇/街道',
      dataIndex: 'town',
      key: 'towndm',
      align: 'center',
      width: 170,
    },
    {
      title: '村名称',
      dataIndex: 'village',
      key: 'villagedm',
      align: 'center',
      width: 150,
    },
    {
      title: '户主姓名',
      dataIndex: 'hzxm',
      key: 'hzxm',
      align: 'center',
      width: 150,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      align: 'center',
      width: 300,
    },
    {
      title: '房屋编号',
      dataIndex: 'fwbh',
      key: 'fwbh',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.town !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row);
          },
        };
      },
    },
    {
      title: '层数',
      dataIndex: 'cs',
      key: 'cs',
      align: 'center',
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'verification_discrepancy',
      key: 'verification_discrepancy',
      align: 'center',
      width: 300,
    },
  ];
  const computedTableData = computed(() => {
    console.log(tableSource.value);
    return tableSource.value;
  });
  // 获取当前标题（响应式）
  const columns = computed(() => {
    const cols = [...baseColumns]; // 创建新数组
    return cols;
  });

  async function getData() {
    console.log('+++++++++++++++++++++++');
    if (startDate.value == null) {
      let currentDate = moment().format('YYYY-MM-DD');
      const start: any = dayjs('2024-01-01');
      const end: any = dayjs(currentDate);
      startDate.value = start;
      endDate.value = end;
    }

    let params: any = {
      pageindex: pageIndex.value,
      pagesize: pageSize.value,
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      cs: cs.value + '',
      remark: remark.value + '',
    };
    console.log('xzq', params);
    if (strXzqm.value != undefined && strXzqm.value != '') {
      params.xzqdm = strXzqm.value[0];
      params.towndm = strXzqm.value[1];
      params.villagedm = strXzqm.value[2];
    }
    let res = await gethousingearlyList(params);
    console.log('xzq', res);
    let list = res.items;
    tableSource.value = list;
    total.value = res.total;
    loading.value = false;
  }

  const getDetailData = async (row: any) => {
    router.push({
      path: '/utils/houseCheckLog',
      query: {
        xzq: row.xzq,
        town: row.towndm,
        village: row.villagedm,
        hzxm: row.hzxm,
        fwbh: row.fwbh,
        startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
        txtKeyWord: txtKeyWord.value,
        xzqdm: row.xzqdm ?? '',
        cs: cs.value + '',
      },
    });
  };
  function handleExport() {
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    let xzqdm = '';
    let towndm = '';
    let villagedm = '';
    if (strXzqm.value[0] != undefined) {
      xzqdm = strXzqm.value[0];
    }
    if (strXzqm.value[1] != undefined) {
      towndm = strXzqm.value[1];
    }
    if (strXzqm.value[2] != undefined) {
      villagedm = strXzqm.value[2];
    }
    downloadByUrl({
      url:
        uriBase +
        '/targeted/export/housingearlyListExport?access_token=' +
        tk +
        '&remark=' +
        remark.value +
        '&cs=' +
        cs.value +
        '&xzqdm=' +
        xzqdm +
        '&towndm=' +
        towndm +
        '&villagedm=' +
        villagedm +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD'),
      target: '_blank',
    });
  }
  function getUserInfo() {
    const userStore = useUserStore();
    // userInfo.value = userStore?.getUserInfo;
  }

  function searchBtn() {
    loading.value = true;
    getData();
  }
  const handleChange = (checkedValues) => {
    console.log('当前选中的楼层:', checkedValues);
    // 处理"全部"选项的特殊逻辑
    if (checkedValues.includes('0')) {
      // 如果选择了"全部"，则只保留"全部"选项
      cs.value = ['0'];
    }
    fetchDataWithCsFilter(cs.value);
  };
  const fetchDataWithCsFilter = (values) => {
    // 构建查询条件
    let condition = '';
    if (!values.includes('0') && values.length > 0) {
      condition = `${values.join(',')}`;
      if (!cs.value.concat(condition)) {
        cs.value.push(condition);
      }
    }
    // 调用API或执行查询
    console.log('查询条件:', condition);
  };
  async function getRegionData() {
    let res: any = await getRegion();
    regionList.value = res;
  }
  const getBack = () => {
    router.go(-1);
  };
  function onChange(value) {
    strXzqm.value = value;
  }
  const getTableHeight = () => {
    setTimeout(() => {
      detailTableHeight.value = window.innerHeight - 200;
    });
  };

  const onShowSizeChange = (pageIndex: number, pageSize: number) => {
    getTableHeight();
  };
  watch(pageSize, () => {
    console.log('pageSize', pageSize.value);
    getData();
  });
  watch(pageIndex, () => {
    console.log('current', pageIndex.value);
    getData();
  });
  onBeforeMount(() => {
    getUserInfo();
  });
  onMounted(() => {
    getRegionData();
    // getTableHeight();
    getData();
  });
  </script>

  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style scoped lang="less">
  #map {
    height: calc(100vh - 140px);
  }
  .x-houseMng-search {
    z-index: 100;
    margin: 6px;
    position: absolute;
  }
  .root-house-mng-main {
    margin: 6px;
  }
  .x-village-tabs {
    width: 60vw;
    margin-top: 6px;
    margin-left: 40px;
    :deep(.ant-form) {
      margin-top: 6px;
    }
  }
</style>
<style>
  .ant-form-item {
    margin-bottom: 15px !important;
  }
</style>
